package Common;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Timer;

import Metadata.AttrMgr;
import Metadata.IndexMgr;
import Metadata.TableMgr;
import SQL.planner.Planner;
import Transaction.Recovery;
import Transaction.Transaction;

import exceptions.DataBaseDupCreatedException;
import exceptions.DataBaseNotFoundException;
import storage.buffer.BufferMgr;
import storage.data.StorageInterface;

public class GoggleDB {
	public static BufferMgr bufferMgr = null;
	public static StorageInterface storageInterface=null;
	public static TableMgr tableMgr;
	public static AttrMgr attrMgr;
	public static IndexMgr indexMgr;
	public static Planner planner;
	public static Timer timer = new Timer () ;
	
	public static Hashtable<Integer,Integer> slotInfo;

	public GoggleDB(String dbFileName, int pages) {
		init(dbFileName, pages);
	}
	
	/**
	 * Initialization of those global instances Such as BufferManage and Storage
	 */
	private void init(String dbFileName, int pages) {
		storageInterface= new StorageInterface();
		bufferMgr = new BufferMgr();
		Transaction tx = new Transaction () ;
		planner = new Planner();
		
		try {
			if (pages == 0) {
				storageInterface.openDB(dbFileName);
			//	Recovery.recoveryDB() ; 
			} else {
				File file = new File ( dbFileName) ;
				if ( file.exists() ) {
					file.delete() ;
				}
				file = new File ( "log.txt") ; 
				if ( file.exists() ) {
					file.delete() ; 
				}
				storageInterface.createDB(tx, dbFileName, pages);
			}
			attrMgr = new AttrMgr("attrCatalog",tx);
			tableMgr = new TableMgr("tableCatalog",tx);
			indexMgr = new IndexMgr("indexCatalog",tx);
			slotInfo = new Hashtable<Integer,Integer> ();
		} catch (Exception e) {
			e.printStackTrace();
			try {
					tx.rollback() ;
				}catch ( Exception e1 ){
					e.printStackTrace();
					System.out.println ( "Initialize Server Error!" ) ; 
				}
			System.exit(0);
		}
		finally{
			try {
			tx.commit() ;
			}catch ( Exception e 	){
				e.printStackTrace();
				System.out.println ( "Initialize Server Error!" ) ; 
			}
		}
	}
		
}
 	